<?php
// 确保已启动会话
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 检查用户是否已登录
if (!isset($_SESSION['user'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => '未登录']);
    exit();
}

// 读取配置文件并建立数据库连接
require 'config.php';

$user = $_SESSION['user'];
$userId = $user['id'];

// 设置响应头为 JSON
header('Content-Type: application/json');

// 定义文件类型映射
$mimeTypeMapping = [
    'image' => 'image',
    'video' => 'video',
    'audio' => 'audio',
    'application/pdf' => 'document',
    'application/msword' => 'document',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'document',
    'application/vnd.ms-excel' => 'document',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'document',
    'application/zip' => 'archive',
    'application/x-rar-compressed' => 'archive',
    'text/plain' => 'text',
    // 添加更多常见的 MIME 类型映射
];

// 处理文件上传
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $upload_dir = 'uploads/' . $userId . '/';
    // 确保上传目录存在
    if (!is_dir($upload_dir)) {
        if (!mkdir($upload_dir, 0755, true)) {
            echo json_encode(['success' => false, 'error' => '创建上传目录失败']);
            exit();
        }
    }

    $originalName = basename($_FILES['file']['name']);
    $mimeType = $_FILES['file']['type'];
    $filesize = intval($_FILES['file']['size']); // 确保是整数

    // 获取访问权限，默认为 'private'
    $access = isset($_POST['access']) && in_array($_POST['access'], ['public', 'private']) ? $_POST['access'] : 'private';

    // 阻止上传 .php 文件
    $fileExt = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
    if ($fileExt === 'php') {
        echo json_encode(['success' => false, 'error' => '不允许上传 PHP 文件。']);
        exit();
    }

    // 文件大小限制
    $maxFileSize = 300 * 1024 * 1024; // 300MB
    if ($filesize > $maxFileSize) {
        echo json_encode(['success' => false, 'error' => '文件大小超过限制 (最大300MB)。']);
        exit();
    }

    // 在文件名前面加上时间戳，保留原文件名
    $timestamp = time();
    $uniqueName = $timestamp . '_' . $originalName;
    $filepath = $upload_dir . $uniqueName;

    // 检查文件是否已存在（虽然添加了时间戳，重复概率极低）
    if (file_exists($filepath)) {
        echo json_encode(['success' => false, 'error' => '文件已存在']);
    } else {
        if (move_uploaded_file($_FILES['file']['tmp_name'], $filepath)) {
            // 映射 MIME 类型到常见类别
            $fileCategory = 'other'; // 默认类别
            foreach ($mimeTypeMapping as $key => $value) {
                if (strpos($mimeType, $key) !== false) {
                    $fileCategory = $value;
                    break;
                }
            }

            // 插入文件信息到数据库，包括原始文件名和访问权限
            try {
                // 确保 $fileCategory 不超过 50 个字符（根据数据库定义调整）
                $fileCategory = substr($fileCategory, 0, 50);

                $stmt = $pdo->prepare('INSERT INTO files (name, original_name, type, size, path, upload_time, user_id, access) VALUES (?, ?, ?, ?, ?, NOW(), ?, ?)');
                $stmt->execute([$uniqueName, $originalName, $fileCategory, $filesize, $filepath, $userId, $access]);
                echo json_encode(['success' => true]);
            } catch (PDOException $e) {
                // 删除已上传的文件
                if (file_exists($filepath)) {
                    unlink($filepath);
                }
                echo json_encode(['success' => false, 'error' => '数据库错误: ' . $e->getMessage()]);
            }
        } else {
            echo json_encode(['success' => false, 'error' => '文件上传失败']);
        }
    }
} else {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => '请求方法不被允许']);
}
?>